<?php

namespace App\Http\Controllers;

use App\Library\WeiXin;
use App\Models\Wechat;
use Illuminate\Http\Request;

class MainController extends Controller{


    //获取数据库对应账号的token
    public function token(Request $request){
        $account = $request->get('id');
        $info = Wechat::where('original_id',$account)
            ->first();
        if($info && $info['cookies'] && $info['wechat_token']){
            $return = ['account'=>$account,'cookie'=>$info['cookies'],'token'=>$info['wechat_token']];
            return $this->returnJson(0,'',$return);
        }
        return $this->returnJson(1,'获取微信数据失败');
    }

    //获取微信二维码
    public function scan(Request $request){
        $account = $request->get('id');
        if (empty($account)) {
            return $this->returnJson(1,'参数错误，请刷新后重试。');
        }
        $wechat = new WeiXin($account);
        $result = $wechat->getScan();
        $return['scan'] = $result;
        return $this->returnJson($result['success'],$result['msg'],$result['other']);
    }


    //验证二维码扫描状态，成功则换取token和cookie并保存数据库
    public function check(Request $request){
        $account = $request->get('id');
        if (empty($account)) {
            return $this->returnJson(1,'参数错误，请刷新后重试。');
        }
        $wechat = new WeiXin($account);
        $result = $wechat->checkScan();
        //扫描成功
        if($result['success'] == 0 && $result['other']['status'] == 1){
            $tokens = $wechat->getToken();
            return $this->returnJson($tokens['success'],$tokens['msg'],$result['other']);
        }
        return $this->returnJson($result['success'],$result['msg'],$result['other']);
    }

}